﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace ScreenCapture.Util
{
    /// <summary>
    /// 
    /// </summary>
    public class JsonConvert
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string ObjectToJson(object o)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(o.GetType());
            MemoryStream memory = new MemoryStream();
            serializer.WriteObject(memory, o);
            byte[] datas = new byte[memory.Length];
            memory.Read(datas, 0, (int)memory.Length);
            return Encoding.UTF8.GetString(datas);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="json"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Object JsonToObject(string json, Type type)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
            MemoryStream memory = new MemoryStream(Encoding.UTF8.GetBytes(json));
            return serializer.ReadObject(memory);
        }
    }
}
